package com.chat.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
@EnableWebSocket
public class ChatController implements WebSocketConfigurer {

    // 存储所有房间的会话和用户信息
    private static final Map<Integer, Map<String, WebSocketSession>> roomSessions = new ConcurrentHashMap<>();
    private static final Map<String, String> usernames = new ConcurrentHashMap<>();
    private static final int MAX_ROOMS = 10;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册10个房间的WebSocket端点
        for (int roomId = 1; roomId <= MAX_ROOMS; roomId++) {
            registry.addHandler(new RoomHandler(roomId), "/chat/room" + roomId)
                    .setAllowedOrigins("*");
            roomSessions.put(roomId, new ConcurrentHashMap<>());
        }
    }

    class RoomHandler extends TextWebSocketHandler {
        private final int roomId;
        private final String CHAT_HISTORY_FILE;

        public RoomHandler(int roomId) {
            this.roomId = roomId;
            this.CHAT_HISTORY_FILE = "data/room"+ roomId+".txt";
        }

        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            String sessionId = session.getId();
            roomSessions.get(roomId).put(sessionId, session);

            // 发送历史消息
            sendChatHistory(session);

            // 不再发送新用户加入通知
        }

        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            String sessionId = session.getId();
            String payload = message.getPayload();

            // 直接从消息中解析用户名和内容
            String username = "匿名用户";
            String content = payload;

            // 检查消息格式是否为 [用户名] 消息内容
            if (payload.startsWith("[") && payload.contains("]")) {
                int endIndex = payload.indexOf("]");
                username = payload.substring(1, endIndex);
                content = payload.substring(endIndex + 1).trim();
            }

            String formattedMessage = formatMessage(username, content);
            broadcastMessage(formattedMessage);
            saveToFile(username, content);
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
            String sessionId = session.getId();
            roomSessions.get(roomId).remove(sessionId);
            usernames.remove(sessionId);

            // 不再发送用户离开通知
        }

        private void broadcastMessage(String message) throws IOException {
            TextMessage textMessage = new TextMessage(message);
            for (WebSocketSession s : roomSessions.get(roomId).values()) {
                if (s.isOpen()) {
                    s.sendMessage(textMessage);
                }
            }
        }

        private String formatMessage(String username, String message) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String timestamp = sdf.format(new Date());
            return String.format("[%s] %s: %s", timestamp, username, message);
        }

        private void sendChatHistory(WebSocketSession session) throws IOException {
            try {
                Path filePath = Paths.get(CHAT_HISTORY_FILE);
                if (Files.exists(filePath)) {
                    List<String> history = Files.readAllLines(filePath);
                    for (String line : history) {
                        if (!line.trim().isEmpty()) {
                            session.sendMessage(new TextMessage(line));
                        }
                    }
                }
            } catch (IOException e) {
                // 文件不存在，忽略
            }
        }

        private synchronized void saveToFile(String username, String message) throws IOException {
            String formatted = formatMessage(username, message) + System.lineSeparator();
            Path filePath = Paths.get(CHAT_HISTORY_FILE);

            // 确保目录存在
            Files.createDirectories(filePath.getParent());

            Files.write(filePath, formatted.getBytes(),
                    StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        }
    }
}